# -*- coding: utf-8 -*-

import gtk
from kiwi.ui.delegates import GladeDelegate
from kiwi.ui.gadgets import quit_if_last

from otica.models.usuarios import Usuario
from otica.db import connect  

class Login(GladeDelegate):
    def __init__(self):
        GladeDelegate.__init__(self,
                          gladefile="login",
                          delete_handler=self.delete_handler)
        self.usu = None
        self.mesagem_label.set_color('red')
        self.connect = connect.get_conection()

    def on_usuario__activate(self, entry):
        self.senha.grab_focus()

    def on_senha__activate(self, entry):
        self._do_login()

    def on_buttonOK__clicked(self, button):
        self._do_login()
        
    def on_buttonCancelar__clicked(self, button):
        gtk.main_quit()
        
    def delete_handler(self, *args):
        gtk.main_quit()
    
    def run(self):
        self.show_all()
        self.focus_topmost()
        gtk.main()
        return self.usu

        
    def _login_falhou(self,mensagem):
        self.mesagem_label.set_text(mensagem)
        self.usuario.grab_focus()
        self.senha.set_text('')
        
    def _do_login(self):
        login = self.usuario.get_text().strip()
        senha = self.senha.get_text().strip()
        try:
            usuario = Usuario.selectBy(self.connect,login=login)[0]
        except IndexError, error:
            self._login_falhou('Usuário inexitente!')
            return 0
        usuario_senha = usuario.senha
        
        if usuario_senha != senha:
            self._login_falhou('Senha inválida!')
        else:
            while gtk.events_pending():
                gtk.main_iteration()
            self.usu = usuario
            self.toplevel.destroy()
            gtk.main_quit()
        
             
            
                
